package com.jian.socks5.tcp.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.socksx.SocksVersion;
import io.netty.handler.codec.socksx.v5.DefaultSocks5InitialResponse;
import io.netty.handler.codec.socksx.v5.Socks5AuthMethod;
import io.netty.handler.codec.socksx.v5.Socks5InitialRequest;
import io.netty.handler.codec.socksx.v5.Socks5InitialResponse;

class Socks5InitialReuqestHandler extends SimpleChannelInboundHandler<Socks5InitialRequest> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.err.println("Socks5InitialReuqestHandler:" + cause.getMessage());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Socks5InitialRequest msg) throws Exception {
        // socks是否认证
        boolean isAuth = false;
        if(msg.decoderResult().isFailure()) {
            System.err.println("不是ss5协议");
            ctx.fireChannelRead(msg);

        }else if (msg.version().equals(SocksVersion.SOCKS5)) {
            System.out.println("询问版本，并询问是否需要认证！" + msg.authMethods());
            Socks5InitialResponse socks5InitialResponse;
            if(isAuth){
                socks5InitialResponse = new DefaultSocks5InitialResponse(Socks5AuthMethod.PASSWORD);
            }else{
                socks5InitialResponse = new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH);
            }
            ctx.writeAndFlush(socks5InitialResponse);
        }
    }
}
